
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Helper;
using IRepository;
using Models;
using System.Linq;
using Models.Entity;
using MySql.Data.MySqlClient;
using Dapper;
using System.Data;
using System.Linq.Expressions;

namespace Repository
{
    /// <summary>
    /// 图片处理服务
    /// </summary>
    public class ClassesCfgRepository : IClassesCfgRepository
    {
        DapperHelper<CClassesCfgEntity> dbHelper = new DapperHelper<CClassesCfgEntity>();
        DapperHelper<CClassesCfgTeacherEntity> dbHelper_teacher = new DapperHelper<CClassesCfgTeacherEntity>();
        DapperHelper<CClassesCfgTeacherClassesEntity> dbHelper_teacher_classes = new DapperHelper<CClassesCfgTeacherClassesEntity>();
        DapperHelper<CClassesCfgTeacherEntityView> dbHelper_teacher_view = new DapperHelper<CClassesCfgTeacherEntityView>();

        /// <param name="inObj">课表信息</param>
        public async Task<CClassesCfgEntity> Single(DtoWeekCourse inObj)
        {
            var ent = await dbHelper.Single(x => x.classes_id == inObj.ClassesId && x.years == inObj.Years && x.num == inObj.Num);
            if (ent == null) return null;
            ent.TeacherCfgList = new List<CClassesCfgTeacherEntity>();
            //查找该配置的所有
            foreach (var item in await dbHelper_teacher.FindAll(X => X.classes_cfg_id == ent.classes_cfg_id))
            {
                item.ClassesIdList = (await dbHelper_teacher_classes.FindAll(x => x.teacher_cfg_id == item.teacher_cfg_id)).Select(x => x.classes_id).ToList();
                ent.TeacherCfgList.Add(item);
            }
            return ent;
        }

        /// <summary>
        /// 删除,没处理事务
        /// </summary>
        /// <param name="key">主键 ID</param>
        /// <returns></returns>
        public async Task<ResultObj<int>> Delete(int key)
        {
            ResultObj<int> reObj = new ResultObj<int>();
            var ent = await dbHelper.Single(x => x.classes_cfg_id == key);

            foreach (var item in await dbHelper_teacher.FindAll(X => X.classes_cfg_id == key))
            {
                await dbHelper_teacher_classes.Delete(x => x.classes_id == ent.classes_id);
            }
            await dbHelper_teacher.Delete(X => X.classes_cfg_id == key);
            reObj.data = await dbHelper.Delete(i => i.classes_cfg_id == key);
            reObj.success = reObj.data > 0;
            return reObj;
        }

        /// <summary>
        /// 保存，没处理事务
        /// </summary>
        /// <param name="inEnt"></param>
        /// <returns></returns>
        public async Task<ResultObj<int>> Save(DtoSave<CClassesCfgEntity> inEnt)
        {

            ResultObj<int> reObj = new ResultObj<int>();
            inEnt.data.create_time = DateTimeHelper.getDateLong(DateTime.Now);
            DapperHelper<CClassesCfgEntity> _dbHelper = new DapperHelper<CClassesCfgEntity>();
            _dbHelper.TranscationBegin();
            try
            {
                DapperHelper<CClassesCfgTeacherEntity> _dbHelper_teacher = new DapperHelper<CClassesCfgTeacherEntity>(_dbHelper.GetConnection(), _dbHelper.GetTransaction());
                DapperHelper<CClassesCfgTeacherClassesEntity> _dbHelper_teacher_classes = new DapperHelper<CClassesCfgTeacherClassesEntity>(_dbHelper.GetConnection(), _dbHelper.GetTransaction());
                //判断该课表是否已经配置
                if (inEnt.data.classes_cfg_id == 0)
                {
                    var single = await _dbHelper.Single(x => x.classes_id == inEnt.data.classes_id);
                    if (single != null)
                    {
                        inEnt.data.classes_cfg_id = single.classes_cfg_id;
                    }
                }
                var opNum = 0;
                //获取需要删除的配置
                var allTeacherCfgId = (await dbHelper_teacher_classes.FindAll(x => x.classes_id == inEnt.data.classes_id)).Select(x => x.teacher_cfg_id).ToList();

                //本次配置过的班级,用于，如果没有配置，则添加配置记录
                List<int> nowCfgClasses = new List<int>();
                foreach (var item in inEnt.data.TeacherCfgList)
                {
                    //合并集全，并去重
                    nowCfgClasses = nowCfgClasses.Union(item.ClassesIdList).ToList();
                    var cfgAlready = (await dbHelper_teacher_view.FindAll(x => x.teacher_course_id == item.teacher_course_id)).Where(x => item.ClassesIdList.Contains(x.classes_id)).Select(x => x.teacher_cfg_id).ToList();
                    allTeacherCfgId = allTeacherCfgId.Union(cfgAlready).ToList();
                }
                if (nowCfgClasses.Count() > 0)
                {
                    //获取已经配置过的
                    List<int> alreadyClassesIdList = (await dbHelper.FindAll($"classes_id in ({string.Join(",", nowCfgClasses)})")).Select(x => x.classes_id).ToList();
                    var addId = nowCfgClasses.Where(x => !alreadyClassesIdList.Contains(x)).ToList();
                    foreach (var item in addId)
                    {
                        inEnt.data.classes_cfg_id = await SequenceRepository.GetNextID<CClassesCfgEntity>();
                        inEnt.data.classes_id = item;
                        opNum = await dbHelper.Save(inEnt);
                        if (opNum < 1)
                        {
                            reObj.msg = "保存失败";
                            reObj.success = false;
                            _dbHelper.TranscationRollback();
                            return reObj;
                        }
                    }
                }
                //删除配置过本班的老师
                string sql = $@"
DELETE  
FROM
        c_classes_cfg_teacher_classes
WHERE
		teacher_cfg_id in ({string.Join(',', allTeacherCfgId)})";
                // Console.WriteLine(sql);
                try
                {
                    opNum = await dbHelper.Exec(sql);
                }
                catch
                {
                }
                //删除本班的所有配置
                sql = $@"
DELETE c_classes_cfg_teacher_classes 
FROM
	c_classes_cfg_teacher_classes,
	c_classes_cfg_teacher 
WHERE
	c_classes_cfg_teacher_classes.teacher_cfg_id = c_classes_cfg_teacher.teacher_cfg_id 
	AND (c_classes_cfg_teacher.classes_cfg_id ={inEnt.data.classes_cfg_id} or c_classes_cfg_teacher_classes.classes_id={inEnt.data.classes_id})";
                // Console.WriteLine(sql);
                opNum = await dbHelper.Exec(sql);

                sql = $@"
DELETE c_classes_cfg_teacher 
FROM
	c_classes_cfg_teacher 
WHERE
	teacher_cfg_id not in (select teacher_cfg_id from c_classes_cfg_teacher_classes)";
                opNum = await dbHelper.Exec(sql);

                if (inEnt.data.classes_cfg_id == 0)
                {
                    inEnt.data.classes_cfg_id = await SequenceRepository.GetNextID<CClassesCfgEntity>();
                    opNum = await dbHelper.Save(inEnt);
                    if (opNum < 1)
                    {
                        reObj.msg = "保存失败";
                        reObj.success = false;
                        _dbHelper.TranscationRollback();
                        return reObj;
                    }
                }
                else
                {
                    reObj.data = await dbHelper.Update(inEnt);

                }

                foreach (var item in inEnt.data.TeacherCfgList)
                {
                    item.teacher_cfg_id = await SequenceRepository.GetNextID<CClassesCfgTeacherEntity>();
                    item.classes_cfg_id = inEnt.data.classes_cfg_id;
                    item.is_use = 0;
                    reObj.data = await dbHelper_teacher.Save(new DtoSave<CClassesCfgTeacherEntity> { data = item });

                    //如果没有配置教师
                    if (item.ClassesIdList == null) item.ClassesIdList = new List<int>() { inEnt.data.classes_id };
                    else if (!item.ClassesIdList.Contains(inEnt.data.classes_id)) item.ClassesIdList.Add(inEnt.data.classes_id);
                    //去掉重复的
                    item.ClassesIdList = item.ClassesIdList.GroupBy(x => x).Select(x => x.Key).ToList();
                    foreach (var item1 in item.ClassesIdList)
                    {
                        await dbHelper_teacher_classes.Save(new DtoSave<CClassesCfgTeacherClassesEntity>
                        {
                            data = new CClassesCfgTeacherClassesEntity
                            {
                                classes_id = item1,
                                teacher_cfg_id = item.teacher_cfg_id
                            }
                        });
                    }
                }
                reObj.success = true;

                _dbHelper.TranscationCommit();
            }
            catch (System.Exception e)
            {
                reObj.success = false;
                reObj.msg = e.Message;
                _dbHelper.TranscationRollback();
            }


            return reObj;
        }

        /// <summary>
        /// 查询单条
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        public async Task<CClassesCfgEntity> SingleByKey(DtoDo<int> inObj)
        {
            var ent = await dbHelper.Single(x => x.classes_cfg_id == inObj.Key);
            if (ent == null) return null;
            ent.TeacherCfgList = new List<CClassesCfgTeacherEntity>();
            //查找该配置的所有
            foreach (var item in await dbHelper_teacher_view.FindAll(X => X.classes_id == ent.classes_id))
            {
                item.ClassesIdList = (await dbHelper_teacher_classes.FindAll(x => x.teacher_cfg_id == item.teacher_cfg_id)).Select(x => x.classes_id).ToList();
                ent.TeacherCfgList.Add(Fun.ClassToCopy<CClassesCfgTeacherEntityView, CClassesCfgTeacherEntity>(item));
            }
            return ent;
        }
    }
}
